#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;

struct Record {
    Record(const string & word, int frequency)
    : _word(word)
    , _frequency(frequency)
    {}

    string _word;
    int _frequency;
};

bool operator<(const Record lhs, const Record rhs){
    // return lhs._word < rhs._word;        //按单词首字符升序
    return lhs._frequency > rhs._frequency; //按词频降序
}

class Dictionary{
public:
    Dictionary(int size) {
        _dict.reserve(size);
    }

    void read(const std::string &filename){
        ifstream ifs(filename);
        if(!ifs){
            cerr << "ifstream open file failed" << endl;
        }

        string line;
        while(getline(ifs, line)){
            string word;
            istringstream iss(line);
            while(iss >> word){
                dealWord(word);
                insert(word);
            }
        }
        sort(_dict.begin(), _dict.end());
        ifs.close();
    }

    void dealWord(string& word){
        auto it = word.begin();
        while(it != word.end()){
            if (!isalpha(*it)){
                it = word.erase(it);
            } else {
                ++it;
            }
        }
    };

    void insert(string word){
        if (word.size() == 0){
            return;
        }

        int index = 0;
        for(; index < _dict.size(); index++){
            if (word == _dict[index]._word){
                _dict[index]._frequency++;
                break;
            }
        }
        if (index == _dict.size()){
            _dict.push_back(Record(word, 1));
        }
    }

    void store(const std::string &filename){
        ofstream ofs(filename);
        if (!ofs){
            cerr << "ofstream file failed" << endl;
        }

        for (int index = 0; index < _dict.size(); index++){
            ofs << _dict[index]._word << " " << _dict[index]._frequency <<endl;
        }

        ofs.close();
    }
private:
    vector<Record> _dict;
};

void test0(){
    Dictionary d1(10000);
    d1.read("The_Holy_Bible.txt");
    d1.store("dict.dat");
}

int main(void){
    test0();
    return 0;
}